def sb = new StringBuffer()

// read file linewise but collect in StringBuffer until [Term]
// then check whether Term only composed with vocabularies we know
new File(args[0]).readLines().each { line ->
    
  // ignore commented lines
  if ( !line.startsWith("!") ) {
    if ( line.trim().equals("[Term]") ) {
      // println sb.toString()
      if (sb.size() > 0 ) {
        def mp = ""
        def l = []
        def splits = sb.toString().split("intersection_of: ")

        if ( splits.size() > 1 ) {
          if ( splits[0].contains("MP:") && splits[0].contains("!")) mp = splits[0].substring(splits[0].indexOf("MP:"), splits[0].indexOf("!")).trim()
          else if ( splits[0].contains("MP:") && splits[0].contains("!")) mp = splits[0].substring(splits[0].indexOf("MP:")).trim()

          splits[1..-1].each { t ->
            if ( t.contains("MA:") && t.contains("!")) {
              l.add(t.substring(t.indexOf("MA:"), t.indexOf("!")).trim())
            } else if ( t.contains("MA:")) {
              l.add(t.substring(t.indexOf("MA:")))
            } else if ( t.contains("PATO:") && t.contains("!")) {
              l.add(t.substring(t.indexOf("PATO:"), t.indexOf("!")).trim())
            } else if ( t.contains("PATO:")) {
              l.add(t.substring(t.indexOf("PATO:")))
            } else if ( t.contains("GO:") && t.contains("!")) {
              l.add(t.substring(t.indexOf("GO:"), t.indexOf("!")).trim())
            } else if ( t.contains("GO:")) {
              l.add(t.substring(t.indexOf("GO:")))
            }
          }
        }

        // println sb.toString()

        // this requires all terms being supported 
        // at the moment only MA, GO and PATO as this is what 
        // pipelines support
        if ( (!mp.equals("")) && (l.size() == (splits.size() - 1) ) ) println mp + "\t" + l.join("\t")
        sb = new StringBuffer()
      }
    } else {
      if (!line.trim().equals("")) { 
        def s = line.trim()
        sb.append(" ")
        sb.append(s)
        // println sb.toString()
      }
    }
  }
}
